<?php
namespace api\modules\v1\models\friend;

use api\modules\v1\models\circle\Circle;
use api\modules\v1\models\circle\CircleUserRelation;
use api\modules\v1\models\group\GroupUser;
use api\modules\v1\models\user\User;
use api\modules\v1\models\user\UserAttention;
use api\modules\v1\models\userLevel\UserLevel;
use common\models\Functions;
use common\models\im\Im;
use common\models\Status;
use Yii;
use yii\base\Exception;
use yii\helpers\ArrayHelper;

class Friend extends \common\models\friend\Friend
{
    /**
     * 好友列表
     * @return array
     */
    public function getList()
    {
        try{
            $page = (int) Yii::$app->request->get('page',1);
            $size = (int) Yii::$app->request->get('size',20);
            $account = (string) Yii::$app->request->get('account','');

            $groupTxCode = (string) Yii::$app->request->get('group_tx_code',"");
            $inGroup = (int) Yii::$app->request->get('in_group',Status::COMMON_RADIO_NO);  // 是否在群里

            $user = (new User()) -> checkUser();

            $andWhere = $where = [];
            $where['user_id'] = $user['id'];
            if ($account) {
                $userIds = User::getFormArrayAndWhere([
                    'status' => 1,
                    'nick_name' => $account,
                ],['like','nick_name',$account],'id','id');

                $andWhere[] = ['or',
                    ['like','friend_phone',$account],
                    ['like','friend_tx_code',$account],
                    ['like','friend_code',$account],
//                ['like','friend_nick_name',$account],
                    ['like','mark',$account],
                    ['in','friend_id',$userIds],
                ];
            }

            if ($groupTxCode && $inGroup == Status::COMMON_RADIO_NO) {
                $groupUserIds = GroupUser::getFormArray(['group_tx_code' => $groupTxCode],'user_id','user_id');
                $andWhere[] = ['not in','friend_id',$groupUserIds];
            }

            $count = static::getCountByAndWhere($where,$andWhere);
            $data = static::setPageinationAPI($page, $size, $count);

            $offset = ($page - 1) * $size;
            $list = static::getObjectByAndWhere($where, $andWhere, ['*'], 'id DESC', $offset, $size)->with([
                'friend' => function ($q) {
                    $q->select(['id','login_name','user_face','nick_name','tx_code','status']);
                },
            ])
                ->asArray()->all();
            $result = [];
            foreach ($list as $v) {
                $singleFriendInfo = ArrayHelper::getValue($v,'friend',[]);
                if ($singleFriendInfo['status'] == Status::COMMON_RADIO_NO) {
                    continue;
                }
                $result[] = [
                    'id' => (int) $singleFriendInfo['id'] ?: '',
                    'phone' => Functions::hiddenPhone($singleFriendInfo['login_name'], 3, 4),
                    'tx_code' => $singleFriendInfo['tx_code'],
                    'face' => static::getAvatar($singleFriendInfo['user_face']),
                    'nick_name' => $singleFriendInfo['nick_name'] ?? '',
                    'qr_code' => static::getImages($singleFriendInfo['qr_code']),
                    'signature' => $singleFriendInfo['signature'] ?: '',
                    'mark' => $v['mark'] ?: '',
                ];
            }

            $data['data'] = $result;
            return Functions::formatRestAPI(0, '', $data);
        } catch (\yii\db\Exception $ee) {
            return Functions::formatRestAPI(1, '服务异常');
        } catch(Exception $e){
            return Functions::formatRestAPI(1,$e->getMessage());
        }
    }

    /**
     * 获取好友信息
     * @param string $code
     * @return array
     */
    public function info($code = 0)
    {
        try{
            if (empty($code)) {
                throw new Exception('参数错误');
            }
            $user = Yii::$app->getUser()->getIdentity()->toArray();
            $levelInfo = UserLevel::getOneInfoById($user['level_id']);

            $where = $andWhere = [];
            $where['tx_code'] = $code;


            list($longitude,$latitude) = $this->getPosition($user['phone']);
            $distanceField = "ROUND(
                6378.138 * 2 * ASIN(
                    SQRT(
                        POW(
                            SIN(
                                (
                                    {$latitude} * PI() / 180 - latitude * PI() / 180
                                ) / 2
                            ),
                            2
                        ) + COS({$latitude} * PI() / 180) * COS(latitude * PI() / 180) * POW(
                            SIN(
                                (
                                    {$longitude} * PI() / 180 - longitude * PI() / 180
                                ) / 2
                            ),
                            2
                        )
                    )
                ),5 
            ) AS distance";

            $friend = User::getObjectByAndWhere($where,$andWhere,['*',$distanceField])->with()->asArray()->one();


            $followList = UserAttention::getByAndWhere(['user_id'=>$user['id'],'type'=>Status::USER_ATTENTION_TYPE_FOLLOW]);
            $followIds = array_column($followList,'topic_id');

            //圈子
            $circleWhere['user_id'] = $friend['id'];
            $circleWhere['is_delete'] = Status::COMMON_IS_NOT_DELETE;
            $circleWhere['status'] = Status::COMMON_CHECKING_SUCCESS;
            $circleWhere['is_see'] = Status::COMMON_RADIO_YES;
            //圈子获赞数量
            $circleLikeNum = (int)CircleUserRelation::getCountByWhere(['topic_user_id'=>$friend['id'],'type'=>Status::CIRCLE_USER_RELATION_TYPE_LIKE])?:0;
            $collect_num = (int)Circle::getSumByWhere($circleWhere,'collect_num')?:0;

            //粉丝数量
            $fansNum = (int)UserAttention::getCountByWhere(['topic_id'=>$friend['id'],'type'=>Status::USER_ATTENTION_TYPE_FOLLOW])?:0;
            //关注数量
            $attentionNum = (int)UserAttention::getCountByWhere(['user_id'=>$friend['id'],'type'=>Status::USER_ATTENTION_TYPE_FOLLOW])?:0;

            //收藏数量
            $userCollect = CircleUserRelation::getCountByWhere(['user_id'=>$friend['id'],'type'=>Status::CIRCLE_USER_RELATION_TYPE_COLLECT])?:0;

            $data = [
                'id' => (int) $friend['id'] ?: '',
//                'phone' => Functions::hiddenPhone($friend['login_name'], 3, 4),
                'tx_code' => $friend['tx_code'],
                'code' => $friend['user_code'],
                'face' => static::getAvatar($friend['user_face']),
                'nick_name' => $friend['nick_name'] ?? '',
                'qr_code' => static::getImages($friend['qr_code']),
                'signature' => $friend['signature'] ?: '',
                'mark' => "",
                #兴趣爱好
                'interests' => array_filter(explode(',',trim($friend['interests'],','))),
                'is_friend' => false,
                'birthday' => $friend['birthday'] ?: '',
                'age' => $friend['birthday'] ? Functions::birthday($friend['birthday']) : 0,
                'sex' => (int) $friend['sex'],
                'sex_name' => Status::COMMON_SEX_MAP[$friend['sex']] ?? '未知',
                'height' => $friend['height'] ? $friend['height'].'CM' : '未知',
                'distance' => round($friend['distance'],2),

                //关注
                'attention_num' => $attentionNum,
                'fans_num' => $fansNum,
                //圈子相关
                'circle_num' => (int)Circle::getCountByWhere($circleWhere),
                'circle_like_num' => $circleLikeNum,
                'circle_collect_num' => $collect_num,
                'circle_all_num' => (int)bcadd($circleLikeNum,$collect_num),
                'is_attention' => in_array($friend['id'],$followIds),
                //收藏数量
                'user_collect_num' => $userCollect,
            ];

            $data['distance'] = User::handleDistance($levelInfo,$friend,$data['distance']);

            //距离
//            if($levelInfo['show_nearby'] == Status::COMMON_RADIO_NO ){
//                $data['distance'] = ">100KM";
//            } else {
////                $data['distance'] = $data['distance'] ? $data['distance'].'KM' : '未知';
//                $data['distance'] = $data['distance'].'KM';
//            }

            //是否是好友
            $isFriendWhere = $isFriendAndWhere = [];
            $isFriendWhere['user_id'] = $user['id'];
            $isFriendWhere['friend_id'] = $friend['id'];
            $isFriend = static::getOneByWhere($isFriendWhere,['id','is_show_circle']);
            if (!empty($isFriend)) {
                $data['mark'] = $isFriend['mark'];
                $data['is_friend'] = true;
                $data['is_show_circle'] = (int) ($isFriend['is_show_circle'] ?? 0);

            }

            // 是否可以查看群
            $currentLevelInfo = UserLevel::getOneByWhere(['id' => $user['level_id']]);
            $data['is_show_group'] = false;
            if ($currentLevelInfo['is_show_group'] == Status::COMMON_RADIO_YES) {
                $data['is_show_group'] = true;
            }

            return Functions::formatRestAPI(0, '', $data);
        } catch (\yii\db\Exception $ee) {
            return Functions::formatRestAPI(1, '服务异常');
        } catch(Exception $e){
            return Functions::formatRestAPI(1,$e->getMessage());
        }
    }

    /**
     * 修改好友信息 - 备注，是否能查看朋友圈
     * @return array
     */
    public function updateMark() {
        $trans = static::getDb()->beginTransaction();

        try {

            $redis = Yii::$app->redis;
            $user = (new User()) -> checkUser();

            $code = Yii::$app->request->post('code','');
            $mark = Yii::$app->request->post('mark','');
            $isShowCircle = Yii::$app->request->post('is_show_circle',0);

            if (!$code) {
                throw new Exception('参数错误！');
            }

            if (!$mark && !$isShowCircle) {
                throw new Exception('参数错误！');
            }

            $where = $andWhere = [];
            $where['tx_code'] = $code;

            $friend = User::getObjectByAndWhere($where,$andWhere)->with()->asArray()->one();
            if (empty($friend)) {
                throw new Exception('好友不存在！');
            }

            //是否是好友
            $isFriendWhere = $isFriendAndWhere = [];
            $isFriendWhere['user_id'] = $user['id'];
            $isFriendWhere['friend_id'] = $friend['id'];
            $isFriend = static::getOneByWhere($isFriendWhere,'id');
            if (empty($isFriend)) {
                throw new Exception('您和他不是好友，不能设置备注！');
            }


            $updateData = $updateImData = [];
            if ($mark) {
                $updateData['mark'] = $mark;
                $updateImData['Tag_SNS_IM_Remark'] = $mark;
            }

            if ($isShowCircle) {
                if (!in_array($isShowCircle,[Status::COMMON_RADIO_YES, Status::COMMON_RADIO_NO])) {
                    throw new Exception('参数不合法！');
                }
                $updateData['is_show_circle'] = $isShowCircle;
                $updateImData['Tag_SNS_Custom_iscircle'] = (string) $isShowCircle;
            }


            if ($updateData) {
                $res = static::updateData($updateData,$isFriendWhere);
                if ($res === false) {
                    throw new Exception('修改失败');
                }
            }


            if ($updateImData) {
                // IM
//            $resIm = (new Im())->updateFriend($user['tx_code'],$friend['tx_code'], $mark);
                $resIm = (new Im())->updateImFriend($user['tx_code'],$friend['tx_code'], $updateImData);
                if (!$resIm) {
                    throw new Exception('修改失败');
                }
            }


            $trans->commit();
            return Functions::formatRestAPI(0, '处理成功');
        } catch (\yii\db\Exception $ee) {
            return Functions::formatRestAPI(1, '服务异常');
        }  catch (Exception $e) {
            $trans->rollBack();
            return Functions::formatRestAPI(1,$e->getMessage());
        }
    }

    /**
     * 删除好友
     * @param string $code
     * @return array
     */
    public function del($code = '') {
        $trans = static::getDb()->beginTransaction();

        try {

            $code = $code ? $code : Yii::$app->request->post('code','');
            if (!$code) {
                throw new Exception('参数错误！');
            }

            $redis = Yii::$app->redis;
            $user = (new User()) -> checkUser();

            $where = $andWhere = [];
            $where['tx_code'] = $code;

            $friend = User::getObjectByAndWhere($where,$andWhere)->asArray()->one();
            if (empty($friend)) {
                throw new Exception('好友不存在！');
            }


            //是否是好友
            $isFriendWhere = $isFriendAndWhere = [];
            $isFriendWhere['user_id'] = $user['id'];
            $isFriendWhere['friend_id'] = $friend['id'];
            $isFriend = static::getOneByWhere($isFriendWhere,'id');
            if (empty($isFriend)) {
                throw new Exception('您和他不是好友，不能删除！');
            }

            // 删除双向好友
            $friendAndWhereOne['user_id'] = $user['id'];
            $friendAndWhereOne['friend_id'] = $friend['id'];
            $res = static::deleteAll($friendAndWhereOne);
            if ($res === false) {
                throw new Exception('删除失败1');
            }

            $friendAndWhereTwo['user_id'] = $friend['id'];
            $friendAndWhereTwo['friend_id'] = $user['id'];
            $res = static::deleteAll($friendAndWhereTwo);
            if ($res === false) {
                throw new Exception('删除失败2');
            }

            // 删除双向好友申请记录
            $friendApplyAndWhere = ['or',
                ['and',
                    ['=','user_id',$user['id']],
                    ['=','friend_id',$friend['id']],
                ],
                ['and',
                    ['=','user_id',$friend['id']],
                    ['=','friend_id',$user['id']],
                ],
            ];
            $res = FriendApply::deleteAll($friendApplyAndWhere);
            if ($res === false) {
                throw new Exception('删除失败3');
            }

//            $attentionData['user_id'] = $user['id'];
//            $attentionData['topic_id'] = $friend['id'];
//            $attentionData['type'] = Status::USER_ATTENTION_TYPE_FOLLOW;
//            UserAttention::deleteAll($attentionData);

            $trans->commit();
            // IM
            $resIm = (new Im())->deleteFriend($user['tx_code'],$friend['tx_code']);
//            $resIm = (new Im())->getFriend($user['tx_code'],$friend['tx_code']);
            if (!$resIm) {
                throw new Exception('删除失败4');
            }
            return Functions::formatRestAPI(0, '删除成功');
        } catch (\yii\db\Exception $ee) {
            return Functions::formatRestAPI(1, '服务异常');
        } catch (Exception $e) {
            $trans->rollBack();
            return Functions::formatRestAPI(1,$e->getMessage());
        }
    }


}
